package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gakki
 * @create 2022/5/1 17:40
 */
@Slf4j
@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    /**
     * 匹配path通配符
     */
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * 过滤器
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        /*
            如果我的请求是： http://localhost:8080/ServletTest/servlet/Hello
            request. getRequestURI() 返回值类似：/ServletTest/servlet/Hello
            request. getRequestURL() 返回值类似：http://localhost:8080/ServletTest/servlet/Hello
        */
        //获取本次请求的uri
        String requestURI = req.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        //放行的uri数组
        String[] uris = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
        };

        //判断本次请求, 是否需要登录
        boolean flag = checkURI(uris, requestURI);

        //如果不需要，则直接放行
        if (flag) {
            log.info("本次请求{}不需要处理！", requestURI);
            chain.doFilter(req, resp);
            return;
        }
        //客户端：判断登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("employee") != null) {
            Long id = (Long) req.getSession().getAttribute("employee");
            log.info("用户已登录，信息为{}", id);
            //在当前线程中设置id，进行传递
            BaseContext.setCurrentId(id);
            chain.doFilter(req, resp);
            return;
        }

        //移动端：判断登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("user") != null) {
            Long id = (Long) req.getSession().getAttribute("user");
            log.info("用户已登录，信息为{}", id);
            //在当前线程中设置id，进行传递
            BaseContext.setCurrentId(id);
            chain.doFilter(req, resp);
            return;
        }

        //如果未登录, 则返回未登录结果
        log.info("用户未登录");
        resp.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    /**
     * uri验证
     * @param uris
     * @param requestUri
     * @return
     */
    private boolean checkURI(String[] uris,String requestUri){
        for (String uri : uris) {
            boolean flag = ANT_PATH_MATCHER.match(uri, requestUri);
            if(flag) {
                return true;
            }
        }
        return false;
    }

}
